package com.cade.agriculturemall.widget;

/**
 * User: Tom
 * Date: 2017-09-11
 * Time: 15:15
 */

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

/**
 * User: Tom
 * Date: 2016-08-22
 * Time: 11:57
 * FIXME
 */
public class HorizontalFlowLayoutManager extends RecyclerView.LayoutManager{

    private LayoutListener mLayoutListener;

    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        detachAndScrapAttachedViews(recycler); // 分离所有的itemView

        int offsetX = getPaddingLeft();
        int offsetY = getPaddingTop();
        int lastHeight = 0;
        int lastWidth = 0;
        for (int i = 0; i < getItemCount(); i++) {
            View scrap = recycler.getViewForPosition(i); // 根据position获取一个碎片view，可以从回收的view中获取，也可能新构造一个

            addView(scrap);
            measureChildWithMargins(scrap, 0, 0);  // 计算此碎片view包含边距的尺寸

            int width = getDecoratedMeasuredWidth(scrap);  // 获取此碎片view包含边距和装饰的宽度width
            int height = getDecoratedMeasuredHeight(scrap); // 获取此碎片view包含边距和装饰的高度height
            boolean aline = mLayoutListener != null && mLayoutListener.excludePosition(i);
            if (aline) {
                offsetX = getPaddingLeft();
                offsetY += lastHeight;
            }else{
                if (offsetX + lastWidth + width > getWidth()) {
                    offsetX = getPaddingLeft();
                    offsetY += lastHeight;
                } else {
                    offsetX += lastWidth;
                }
            }
            layoutDecorated(scrap, offsetX , offsetY, offsetX + width, offsetY + height); // Important！布局到RecyclerView容器中，所有的计算都是为了得出任意position的item的边界来布局
            lastHeight = height;
            lastWidth = width;
            if (aline) {
                lastWidth = 0;
                offsetX = getPaddingLeft();
                offsetY += lastHeight;
            }
        }
    }

    public void setLayoutListener(LayoutListener layoutListener) {
        mLayoutListener = layoutListener;
    }

    public interface LayoutListener{
        boolean excludePosition(int position);
    }

}
